/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.risk.service.impl;


import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.risk.bean.KeyWork;
import com.koron.risk.bean.KeyWorkDetail;
import com.koron.risk.mapper.KeyWorkMapper;
import com.koron.risk.service.api.KeyWorkService;
import com.koron.risk.util.Constants;
import com.koron.system.utils.BusinessCode;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.util.*;

@Service
@SuppressWarnings("deprecation")
public class KeyWorkServiceImpl implements KeyWorkService {
    private final static Logger logger= LoggerFactory.getLogger(KeyWorkServiceImpl.class);
    @Override
    public MessageBean queryForList(StaffBean user, String corpCode, String workName, String departmentCode, Integer page, Integer pageSize) {
        MessageBean<DataBean<Map>> msg = new MessageBean<>();
        if (user == null) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("请先登录系统");
            return msg;
        }
        try (SessionFactory factory = new SessionFactory()) {
            KeyWorkMapper mapper = factory.getMapper(KeyWorkMapper.class);
            // 查询
            Map map = new HashMap();
            map.put("workName", workName);
            map.put("corpCode", corpCode);
            map.put("departmentCode", departmentCode);
            page = (page == null || page < 1) ? 1 : page;
            pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;
            int pageStart = (page - 1) * pageSize;
            map.put("pageStart", pageStart);
            map.put("pageStop", pageSize);
            List<Map> list = mapper.queryForList(map);
            Optional.ofNullable(list).ifPresent(l -> {
                l.stream().forEach(map1 -> {
                    // 如果确认人是 登录用户，则显示 可以确认
                    if (user.getCode().equals(Optional.ofNullable(map1.get("personCode")).orElse("").toString())) {
                        map1.put("flagAffirm", "1");
                    } else {
                        map1.put("flagAffirm", "0");
                    }
                });
            });
            DataBean<Map> dataBean = new DataBean<>();
            dataBean.setList(list);
            dataBean.setPageSize(pageSize);
            dataBean.setPageNo(page);
            // 总条数
            Integer totalNumber = mapper.countForList(map);
            int num = totalNumber / pageSize;
            // 总页数
            Integer totalPage = totalNumber % pageSize == 0 ? num : num + 1;
            dataBean.setTotalNumber(totalNumber);
            dataBean.setTotalPage(totalPage);
            msg.setData(dataBean);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean queryById(String id) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        try (SessionFactory factory = new SessionFactory()) {
            KeyWorkMapper mapper = factory.getMapper(KeyWorkMapper.class);
            Map bean = mapper.queryById(id);
            if (bean == null) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("没有查询到该重点工作,请刷新页面！");
            } else {
                List<KeyWorkDetail> details = mapper.queryByKeyWorkId(id);
                bean.put("workList", details);
            }
            msg.setData(bean);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean insertKeyWork(StaffBean user, KeyWork keyWork, List<KeyWorkDetail> keyWorkDetails) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "保存成功", void.class);
        // 参数校验
        if (user == null) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("请先登录系统");
            return msg;
        }
        if (StringUtils.isEmpty(keyWork.getCorpCode()) || StringUtils.isEmpty(keyWork.getCorpName())) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("水司信息不能为空");
            return msg;
        }
        if (StringUtils.isEmpty(keyWork.getWorkName()) || StringUtils.isEmpty(keyWork.getPersonCode())
                || StringUtils.isEmpty(keyWork.getPersonName())) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("请填写完整任务基本信息");
            return msg;
        }
        if (keyWorkDetails == null || keyWorkDetails.size() == 0) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("请填写重点工作任务信息");
            return msg;
        }
        if (user.getCode().equals(keyWork.getPersonCode())) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("确认人不能是当前登录人员");
            return msg;
        }
        // 奥港供水的部门信息不能为空
        if (Constants.AGGS_CORPCODE.equals(keyWork.getCorpCode())
                && (StringUtils.isEmpty(keyWork.getDepartmentCode()) || StringUtils.isEmpty(keyWork.getDepartmentName()))
        ) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("奥港供水的部门信息不能为空!");
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            KeyWorkMapper mapper = factory.getMapper(KeyWorkMapper.class);
            String keyWorkId = DefaultIdGenerator.getInstance().generateLongId();
            keyWork.setId(keyWorkId);
            // 任务状态(0-未确认 1-已确认)
            keyWork.setState("0");
            Date date = new Date();
            keyWork.setAddTime(date);
            keyWork.setAddUser(user.getCode());
            keyWork.setAddUserName(user.getName());
            keyWork.setUpdateTime(date);
            keyWork.setUpdateUser(user.getCode());
            keyWork.setUpdateUserName(user.getName());
            // 新增重点工作
            mapper.insertKeyWork(keyWork);
            for (KeyWorkDetail keyWorkDetail : keyWorkDetails) {
                if (StringUtils.isEmpty(keyWorkDetail.getContext())) {
                    msg.setCode(BusinessCode.EXCEPTION.getCode());
                    msg.setDescription("工作内容信息不完整");
                    factory.close(false);
                    return msg;
                }
                keyWorkDetail.setId(DefaultIdGenerator.getInstance().generateLongId());
                keyWorkDetail.setKeyWorkId(keyWorkId);
            }
            // 批量 新增重点工作明细
            mapper.insertBatchKeyWorkDetail(keyWorkDetails);
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription("保存失败");
        }
        return msg;
    }

    @Override
    public MessageBean updateKeyWork(StaffBean user, KeyWork keyWork, List<KeyWorkDetail> keyWorkDetails) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "修改成功", void.class);
        if (StringUtils.isEmpty(keyWork.getId())) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("缺少必要参数");
            return msg;
        }
        // 参数校验
        if (user == null) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("请先登录系统");
            return msg;
        }
        if (StringUtils.isEmpty(keyWork.getCorpCode()) || StringUtils.isEmpty(keyWork.getCorpName())) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("水司信息不能为空");
            return msg;
        }
        if (StringUtils.isEmpty(keyWork.getWorkName()) || StringUtils.isEmpty(keyWork.getPersonCode())
                || StringUtils.isEmpty(keyWork.getPersonName())) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("请填写完整任务基本信息");
            return msg;
        }
        if (keyWorkDetails == null || keyWorkDetails.size() == 0) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("请填写重点工作任务信息");
            return msg;
        }
        if (user.getCode().equals(keyWork.getPersonCode())) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("确认人不能是当前登录人员");
            return msg;
        }
        // 奥港供水的部门信息不能为空
        if (Constants.AGGS_CORPCODE.equals(keyWork.getCorpCode())
                && (StringUtils.isEmpty(keyWork.getDepartmentCode()) || StringUtils.isEmpty(keyWork.getDepartmentName()))
        ) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("奥港供水的部门信息不能为空!");
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            KeyWorkMapper mapper = factory.getMapper(KeyWorkMapper.class);
            Map bean = mapper.queryById(keyWork.getId());
            if (bean == null) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("该重点工作已失效，请刷新页面");
                return msg;
            }
            // 如果已确认，不允许修改
            if ("1".equals(bean.get("state").toString())) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("该重点工作已确认，不允许修改");
                return msg;
            }
            keyWork.setUpdateTime(new Date());
            keyWork.setUpdateUser(user.getCode());
            keyWork.setUpdateUserName(user.getName());
            // 修改重点工作
            int i = mapper.updateKeyWork(keyWork);
            if (i != 1) {
                throw new Exception();
            }
            // 根据重点工作id 删除所有 重点工作明细
            mapper.deleteDetailByKeyWorkId(keyWork.getId());
            for (KeyWorkDetail keyWorkDetail : keyWorkDetails) {
                if (StringUtils.isEmpty(keyWorkDetail.getContext())) {
                    msg.setCode(BusinessCode.EXCEPTION.getCode());
                    msg.setDescription("工作内容信息不完整");
                    factory.close(false);
                    return msg;
                }
                keyWorkDetail.setId(DefaultIdGenerator.getInstance().generateLongId());
                keyWorkDetail.setKeyWorkId(keyWork.getId());
            }
            // 批量 新增重点工作明细
            mapper.insertBatchKeyWorkDetail(keyWorkDetails);
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription("修改失败");
        }
        return msg;
    }

    @Override
    public MessageBean affirmKeyWork(StaffBean user, String id) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "确认成功", void.class);
        if (user == null) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("请先登录系统");
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            KeyWorkMapper mapper = factory.getMapper(KeyWorkMapper.class);
            Map bean = mapper.queryById(id);
            if (bean == null) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("该重点工作已失效，请刷新页面");
                return msg;
            }
            // 判断确认人是否是该用户，如果不是，不允许确认
            if (!user.getCode().equals(Optional.ofNullable(bean.get("personCode")).orElse("").toString())) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("该重点工作确认人已修改");
                return msg;
            }
            // 确认
            if (mapper.affirmKeyWork(id, "1") != 1) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("确认失败");
                return msg;
            }
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription("确认失败");
        }
        return msg;
    }
}
